<?php
namespace App\Plugins;
use Hyperf\Config\Annotation\Value;
class Meituan
{

    /**
     * @Value("appconfig.meituan.appKey")
     */
    private $appKey;

    /**
     * @Value("appconfig.meituan.androidAppKey")
     */
    private $androidAppKey;

    /**
     * @Value("appconfig.meituan.secretKey")
     */
    private $secretKey;


    /**
     *
    0	默認 1	待支付 2	已支付 3	已退款 4	已完成 5	已失效 6	已結算 11	已取消
    订单状态，外卖、话费、闪购、优选、酒店订单会返回该字段
    1 已付款
    8 已完成
    9 已退款或风控
     */
    public $status = [
        1 => 2,
        8 => 6,
        9 => 3,
    ];


    public function createdSign($params)
    {
        ksort($params);
        $str = $this->secretKey; // $secret为分配的密钥
        foreach($params as $key => $value) {
            $str .= $key . $value;
        }
        $str .= $this->secretKey;
        $sign = md5($str);
        return $sign;
    }



    public function getGenerateLink($user_id,$actId,$osType='2'){
        $responseResult['url']= $this->getMeituanUrlLink($user_id,$actId,2,$osType);
        $responseResult['short_url']='';//$this->getMeituanUrlLink($user_id,$actId,1);
        $responseResult['path']=$this->getMeituanUrlLink($user_id,$actId,4,$osType);
        $responseResult["qrcode_url"]=$this->erCodeCode($user_id,$actId,$osType);
        return $responseResult;
    }


    /**
     * 获取美团链接
     */
    private function getMeituanUrlLink($user_id,$actId,$linkType,$osType="2"){
        $data['actId'] = $actId;
        $data['appkey'] = $osType == "1" ? $this->appKey : $this->androidAppKey;
        $data['sid'] = $user_id;
        $data['linkType'] = $linkType;
        $data['sign'] = $this->createdSign($data);
        $url = "https://openapi.meituan.com/api/generateLink?".http_build_query($data);
        $responseMsg = requestGet($url);
        if($responseMsg['status'] == 0){
            return $responseMsg['data'];
//            return ['status'=>true,'msg'=>'获取成功','data'=>$responseMsg['data']];
        }else{
            return "";
//            return ['status'=>false,'msg'=>$responseMsg['des']];
        }
    }


    /**
     * 获取美团二维码
     */
    private function erCodeCode($user_id,$actId,$osType="2"){
        $data['actId'] = $actId;
        $data['appkey'] = $osType=="1" ? $this->appKey : $this->androidAppKey;
        $data['sid'] = $user_id;
        $data['sign'] = $this->createdSign($data);
        $url = "https://openapi.meituan.com/api/miniCode?".http_build_query($data);
        $responseMsg = requestGet($url);
        if($responseMsg['status'] == 0){
            return $responseMsg['data'];
//            return ['status'=>true,'msg'=>'获取成功','data'=>$responseMsg['data']];
        }else{
            return "";
//            return ['status'=>false,'msg'=>$responseMsg['des']];
        }
    }



    /**
     *
     * 订单处理
     */
    public function returnOrderDeal($data,$method="list")
    {
        $responseTurnData = [];
        foreach ($data as $k => $v) {
            $orderSrc=10;
            $orderSrcName = "美团团购";
            $images = "https://jzcloud.jiruan.ltd/meituan.jpg";
            if($v['businessLine'] == 2){
                $orderSrc = 7;
                $orderSrcName = "外卖/闪购";
                $images="https://jzcloud.jiruan.ltd/meituan_waimai.jpg";
            }elseif ($v['businessLine'] == 3){
                $orderSrc = 9;
                $orderSrcName = "美团酒店";
                $images="https://jzcloud.jiruan.ltd/meituan_jiudian.jpg";
            }elseif ($v['businessLine'] == 4){
                $orderSrc = 8;
                $orderSrcName = "美团优选";
                $images="https://jzcloud.jiruan.ltd/meituan_youxuan.jpg";
            }elseif ($v['businessLine'] == 1 || $v['businessLine'] == 5){
                $orderSrc = 10;
                $orderSrcName = "美团团购";
                $images="https://jzcloud.jiruan.ltd/meituan_shangchao.jpg";
            }


            if($orderSrc==9){           //酒店
                $smstitle = json_decode($v['smstitle'],true);
                if($smstitle && isset($smstitle['roomName'])){
                    $v['smstitle'] = $smstitle['roomName'];
                }
            }

            if($method=="list") {       //列表数据
                $turnData = [
                    'orderId' => $v['orderid'],
                    'orderStatus' => isset($this->status[$v['status']]) ? $this->status[$v['status']] : 11,
                    'orderSrc' => $orderSrc,
                    'tag' => "美团",
                    'tagItem' => $orderSrcName,
                    'name' => $v['smstitle'],
                    'goodsId' => isset($v['actId']) ? $v['actId'] : '',
                    'images' => $images,
                    'rid' => isset($v['sid']) ? $v['sid'] : 0,
                    'shopName' => "",
                    'price' => isset($v['total']) && !empty($v['total']) ? $v['total'] : 0,
                    'orderType' => 1,
                    'payMoney' => isset($v['payprice']) && !empty($v['payprice']) ? $v['payprice'] : 0,
                    'rebateAmount' => $v['profit'],
                    'incomeRate' => $v['profit'] / $v['payprice'],
                    'orderCreateTime' => isset($v['paytime']) && $v['paytime'] ? date("Y-m-d H:i:s", $v['paytime']) : null,
                    'orderPaidTime' => isset($v['paytime']) && $v['paytime'] ? date("Y-m-d H:i:s", $v['paytime']) : null,
                    'orderEarningTime' => isset($v['paytime']) && $v['paytime'] && $this->status[$v['status']] == 6 ? date("Y-m-d H:i:s", $v['paytime']) : null,
                    'settleTime' => isset($v['paytime']) && $v['paytime'] && $this->status[$v['status']] == 6 ? date("Y-m-d H:i:s", $v['paytime']) : null,
                ];
            }else{          //订单回调数据
                $turnData = [
                    'orderId' => $v['orderid'],
                    'orderStatus' => isset($this->status[$v['status']]) ? $this->status[$v['status']] : 11,
                    'orderSrc' => $orderSrc,
                    'tag' => "美团",
                    'tagItem' => $orderSrcName,
                    'name' => $v['smstitle'],
                    'goodsId' => isset($v['actId']) ? $v['actId'] : '',
                    'images' => $images,
                    'rid' => isset($v['sid']) ? $v['sid'] : 0,
                    'shopName' => "",
                    'price' => isset($v['payPrice']) && !empty($v['payPrice']) ? $v['payPrice'] : 0,
                    'orderType' => 1,
                    'payMoney' => isset($v['payPrice']) && !empty($v['payPrice']) ? $v['payPrice'] : 0,
                    'rebateAmount' => isset($v['payPrice']) && !empty($v['payPrice']) ? $v['payPrice'] * $v['ratio'] : 0,
                    'incomeRate' => $v['ratio'],
                    'orderCreateTime' => isset($v['ordertime']) && $v['ordertime'] ? date("Y-m-d H:i:s", $v['ordertime']) : null,
                    'orderPaidTime' => isset($v['paytime']) && $v['paytime'] ? date("Y-m-d H:i:s", $v['paytime']) : null,
                    'orderEarningTime' => isset($v['modTime']) && $v['modTime'] && $this->status[$v['status']] == 6 ? date("Y-m-d H:i:s", $v['modTime']) : null,
                    'settleTime' => isset($v['paytime']) && $v['paytime'] && $this->status[$v['status']] == 6 ? date("Y-m-d H:i:s", $v['paytime']) : null,
                ];
            }
            $responseTurnData[] = $turnData;
        }
        return $responseTurnData;
    }






    /**
     * 美团订单
     */
    public function getOrder($startTime,$endTime,$page=1,$businessLine=2,$responseMsgDataResult=[],$osType="2"){
        $h_params['appkey'] = $osType == "1" ? $this->appKey : $this->androidAppKey;
        $h_params['ts'] = time().'';
        $h_params['businessLine'] = $businessLine;
        $h_params['startTime'] = strtotime($startTime).'';
        $h_params['endTime'] = strtotime($endTime).'';
        $h_params['page'] = "{$page}";
        $h_params['limit'] = "100";
        $h_params['sign'] = $this->createdSign($h_params);
        $url="https://openapi.meituan.com/api/orderList?".http_build_query($h_params);
        $responseMsg = requestGet($url);
        if(isset($responseMsg['total']) && $responseMsg['total'] != 0){
            if ($responseMsg['dataList'] == [] && $responseMsgDataResult) {
                return [];
            }
            if ($responseMsg['dataList'] != []) {
                if ($responseMsgDataResult == []) {
                    $responseMsgDataResult = $responseMsg['dataList'];
                } else {
                    $responseMsgDataResult = array_merge($responseMsgDataResult, $responseMsg['dataList']);
                }
            }
            if ($responseMsg['dataList'] != []) {
                $this->getOrder($startTime, $endTime, $page+1,$businessLine, $responseMsgDataResult);
            }
//            foreach($responseMsgDataResult as $key=>&$value){
//                $value['orderDetail'] = $this->getOrderDetail($value['orderid'],$value['actId']);
//            }
            return $this->returnOrderDeal($responseMsgDataResult);

        }else{
            return [];
        }

    }


    /**
     * 获取订单详情
     * @param $orderId
     * @param $actId
     */
    public function getOrderDetail($orderId,$actId){
        $h_params['appkey']  =$this->appKey;
        $h_params['actId'] = $actId;
        $h_params['full'] = 1;
        $h_params['orderId'] = $orderId;
        $h_params['sign'] = $this->createdSign($h_params);
        $url="https://openapi.meituan.com/api/order?".http_build_query($h_params);
        $responseMsg = requestGet($url);
        if($responseMsg['status'] == 0){
            if(isset($responseMsg['data']) && $responseMsg['data']){
                return $responseMsg['data'];
            }else{
                return [];
            }
        }else{
            return [];
        }
    }



}
